
<!DOCTYPE HTML>
<html lang="" >
    <head>
        <meta charset="UTF-8">
        <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
        <title>Example: Reddit API · GitBook</title>
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="description" content="">
        <meta name="generator" content="GitBook 3.2.2">
        
        
        
    
    <link rel="stylesheet" href="../gitbook/style.css">

    
            
                
                <link rel="stylesheet" href="../gitbook/gitbook-plugin-highlight/website.css">
                
            
                
                <link rel="stylesheet" href="../gitbook/gitbook-plugin-search/search.css">
                
            
                
                <link rel="stylesheet" href="../gitbook/gitbook-plugin-fontsettings/website.css">
                
            
        

    

    
        
    
        
    
        
    
        
    
        
    
        
    

        
    
    
    <meta name="HandheldFriendly" content="true"/>
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <link rel="apple-touch-icon-precomposed" sizes="152x152" href="../gitbook/images/apple-touch-icon-precomposed-152.png">
    <link rel="shortcut icon" href="../gitbook/images/favicon.ico" type="image/x-icon">

    
    
    <link rel="prev" href="UsageWithReactRouter.html" />
    

    </head>
    <body>
        
<div class="book">
    <div class="book-summary">
        
            
<div id="book-search-input" role="search">
    <input type="text" placeholder="Type to search" />
</div>

            
                <nav role="navigation">
                


<ul class="summary">
    
    

    

    
        
        
    
        <li class="chapter " data-level="1.1" data-path="../">
            
                <a href="../">
            
                    
                    Read Me
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.2" data-path="../introduction/">
            
                <a href="../introduction/">
            
                    
                    Introduction
            
                </a>
            

            
            <ul class="articles">
                
    
        <li class="chapter " data-level="1.2.1" data-path="../introduction/Motivation.html">
            
                <a href="../introduction/Motivation.html">
            
                    
                    Motivation
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.2.2" data-path="../introduction/CoreConcepts.html">
            
                <a href="../introduction/CoreConcepts.html">
            
                    
                    Core Concepts
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.2.3" data-path="../introduction/ThreePrinciples.html">
            
                <a href="../introduction/ThreePrinciples.html">
            
                    
                    Three Principles
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.2.4" data-path="../introduction/PriorArt.html">
            
                <a href="../introduction/PriorArt.html">
            
                    
                    Prior Art
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.2.5" data-path="../introduction/Ecosystem.html">
            
                <a href="../introduction/Ecosystem.html">
            
                    
                    Ecosystem
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.2.6" data-path="../introduction/Examples.html">
            
                <a href="../introduction/Examples.html">
            
                    
                    Examples
            
                </a>
            

            
        </li>
    

            </ul>
            
        </li>
    
        <li class="chapter " data-level="1.3" data-path="../basics/">
            
                <a href="../basics/">
            
                    
                    Basics
            
                </a>
            

            
            <ul class="articles">
                
    
        <li class="chapter " data-level="1.3.1" data-path="../basics/Actions.html">
            
                <a href="../basics/Actions.html">
            
                    
                    Actions
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.3.2" data-path="../basics/Reducers.html">
            
                <a href="../basics/Reducers.html">
            
                    
                    Reducers
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.3.3" data-path="../basics/Store.html">
            
                <a href="../basics/Store.html">
            
                    
                    Store
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.3.4" data-path="../basics/DataFlow.html">
            
                <a href="../basics/DataFlow.html">
            
                    
                    Data Flow
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.3.5" data-path="../basics/UsageWithReact.html">
            
                <a href="../basics/UsageWithReact.html">
            
                    
                    Usage with React
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.3.6" data-path="../basics/ExampleTodoList.html">
            
                <a href="../basics/ExampleTodoList.html">
            
                    
                    Example: Todo List
            
                </a>
            

            
        </li>
    

            </ul>
            
        </li>
    
        <li class="chapter " data-level="1.4" data-path="./">
            
                <a href="./">
            
                    
                    Advanced
            
                </a>
            

            
            <ul class="articles">
                
    
        <li class="chapter " data-level="1.4.1" data-path="AsyncActions.html">
            
                <a href="AsyncActions.html">
            
                    
                    Async Actions
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.4.2" data-path="AsyncFlow.html">
            
                <a href="AsyncFlow.html">
            
                    
                    Async Flow
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.4.3" data-path="Middleware.html">
            
                <a href="Middleware.html">
            
                    
                    Middleware
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.4.4" data-path="UsageWithReactRouter.html">
            
                <a href="UsageWithReactRouter.html">
            
                    
                    Usage with React Router
            
                </a>
            

            
        </li>
    
        <li class="chapter active" data-level="1.4.5" data-path="ExampleRedditAPI.html">
            
                <a href="ExampleRedditAPI.html">
            
                    
                    Example: Reddit API
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.4.6" >
            
                <span>
            
                    
                    Next Steps
            
                </span>
            

            
        </li>
    

            </ul>
            
        </li>
    
        <li class="chapter " data-level="1.5" data-path="../recipes/">
            
                <a href="../recipes/">
            
                    
                    Recipes
            
                </a>
            

            
            <ul class="articles">
                
    
        <li class="chapter " data-level="1.5.1" data-path="../recipes/MigratingToRedux.html">
            
                <a href="../recipes/MigratingToRedux.html">
            
                    
                    Migrating to Redux
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.2" data-path="../recipes/UsingObjectSpreadOperator.html">
            
                <a href="../recipes/UsingObjectSpreadOperator.html">
            
                    
                    Using Object Spread Operator
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.3" data-path="../recipes/ReducingBoilerplate.html">
            
                <a href="../recipes/ReducingBoilerplate.html">
            
                    
                    Reducing Boilerplate
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.4" data-path="../recipes/ServerRendering.html">
            
                <a href="../recipes/ServerRendering.html">
            
                    
                    Server Rendering
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.5" data-path="../recipes/WritingTests.html">
            
                <a href="../recipes/WritingTests.html">
            
                    
                    Writing Tests
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.6" data-path="../recipes/ComputingDerivedData.html">
            
                <a href="../recipes/ComputingDerivedData.html">
            
                    
                    Computing Derived Data
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.7" data-path="../recipes/ImplementingUndoHistory.html">
            
                <a href="../recipes/ImplementingUndoHistory.html">
            
                    
                    Implementing Undo History
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.8" data-path="../recipes/IsolatingSubapps.html">
            
                <a href="../recipes/IsolatingSubapps.html">
            
                    
                    Isolating Subapps
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.9" data-path="../recipes/StructuringReducers.html">
            
                <a href="../recipes/StructuringReducers.html">
            
                    
                    Structuring Reducers
            
                </a>
            

            
            <ul class="articles">
                
    
        <li class="chapter " data-level="1.5.9.1" data-path="../recipes/reducers/PrerequisiteConcepts.html">
            
                <a href="../recipes/reducers/PrerequisiteConcepts.html">
            
                    
                    Prerequisite Concepts
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.9.2" data-path="../recipes/reducers/BasicReducerStructure.html">
            
                <a href="../recipes/reducers/BasicReducerStructure.html">
            
                    
                    Basic Reducer Structure
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.9.3" data-path="../recipes/reducers/SplittingReducerLogic.html">
            
                <a href="../recipes/reducers/SplittingReducerLogic.html">
            
                    
                    Splitting Reducer Logic
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.9.4" data-path="../recipes/reducers/RefactoringReducersExample.html">
            
                <a href="../recipes/reducers/RefactoringReducersExample.html">
            
                    
                    Refactoring Reducers Example
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.9.5" data-path="../recipes/reducers/UsingCombineReducers.html">
            
                <a href="../recipes/reducers/UsingCombineReducers.html">
            
                    
                    Using combineReducers
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.9.6" data-path="../recipes/reducers/BeyondCombineReducers.html">
            
                <a href="../recipes/reducers/BeyondCombineReducers.html">
            
                    
                    Beyond combineReducers
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.9.7" data-path="../recipes/reducers/NormalizingStateShape.html">
            
                <a href="../recipes/reducers/NormalizingStateShape.html">
            
                    
                    Normalizing State Shape
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.9.8" data-path="../recipes/reducers/UpdatingNormalizedData.html">
            
                <a href="../recipes/reducers/UpdatingNormalizedData.html">
            
                    
                    Updating Normalized Data
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.9.9" data-path="../recipes/reducers/ReusingReducerLogic.html">
            
                <a href="../recipes/reducers/ReusingReducerLogic.html">
            
                    
                    Reusing Reducer Logic
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.9.10" data-path="../recipes/reducers/ImmutableUpdatePatterns.html">
            
                <a href="../recipes/reducers/ImmutableUpdatePatterns.html">
            
                    
                    Immutable Update Patterns
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.9.11" data-path="../recipes/reducers/InitializingState.html">
            
                <a href="../recipes/reducers/InitializingState.html">
            
                    
                    Initializing State
            
                </a>
            

            
        </li>
    

            </ul>
            
        </li>
    
        <li class="chapter " data-level="1.5.10" data-path="../recipes/UsingImmutableJS.html">
            
                <a href="../recipes/UsingImmutableJS.html">
            
                    
                    Using Immutable.JS with Redux
            
                </a>
            

            
        </li>
    

            </ul>
            
        </li>
    
        <li class="chapter " data-level="1.6" data-path="../FAQ.html">
            
                <a href="../FAQ.html">
            
                    
                    FAQ
            
                </a>
            

            
            <ul class="articles">
                
    
        <li class="chapter " data-level="1.6.1" data-path="../faq/General.html">
            
                <a href="../faq/General.html">
            
                    
                    General
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.6.2" data-path="../faq/Reducers.html">
            
                <a href="../faq/Reducers.html">
            
                    
                    Reducers
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.6.3" data-path="../faq/OrganizingState.html">
            
                <a href="../faq/OrganizingState.html">
            
                    
                    Organizing State
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.6.4" data-path="../faq/StoreSetup.html">
            
                <a href="../faq/StoreSetup.html">
            
                    
                    Store Setup
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.6.5" data-path="../faq/Actions.html">
            
                <a href="../faq/Actions.html">
            
                    
                    Actions
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.6.6" data-path="../faq/ImmutableData.html">
            
                <a href="../faq/ImmutableData.html">
            
                    
                    Immutable Data
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.6.7" data-path="../faq/CodeStructure.html">
            
                <a href="../faq/CodeStructure.html">
            
                    
                    Code Structure
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.6.8" data-path="../faq/Performance.html">
            
                <a href="../faq/Performance.html">
            
                    
                    Performance
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.6.9" data-path="../faq/ReactRedux.html">
            
                <a href="../faq/ReactRedux.html">
            
                    
                    React Redux
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.6.10" data-path="../faq/Miscellaneous.html">
            
                <a href="../faq/Miscellaneous.html">
            
                    
                    Miscellaneous
            
                </a>
            

            
        </li>
    

            </ul>
            
        </li>
    
        <li class="chapter " data-level="1.7" data-path="../Troubleshooting.html">
            
                <a href="../Troubleshooting.html">
            
                    
                    Troubleshooting
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.8" data-path="../Glossary.html">
            
                <a href="../Glossary.html">
            
                    
                    Glossary
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.9" data-path="../api/">
            
                <a href="../api/">
            
                    
                    API Reference
            
                </a>
            

            
            <ul class="articles">
                
    
        <li class="chapter " data-level="1.9.1" data-path="../api/createStore.html">
            
                <a href="../api/createStore.html">
            
                    
                    createStore
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.9.2" data-path="../api/Store.html">
            
                <a href="../api/Store.html">
            
                    
                    Store
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.9.3" data-path="../api/combineReducers.html">
            
                <a href="../api/combineReducers.html">
            
                    
                    combineReducers
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.9.4" data-path="../api/applyMiddleware.html">
            
                <a href="../api/applyMiddleware.html">
            
                    
                    applyMiddleware
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.9.5" data-path="../api/bindActionCreators.html">
            
                <a href="../api/bindActionCreators.html">
            
                    
                    bindActionCreators
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.9.6" data-path="../api/compose.html">
            
                <a href="../api/compose.html">
            
                    
                    compose
            
                </a>
            

            
        </li>
    

            </ul>
            
        </li>
    
        <li class="chapter " data-level="1.10" data-path="../CHANGELOG.md">
            
                <span>
            
                    
                    Change Log
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.11" data-path="../PATRONS.md">
            
                <span>
            
                    
                    Patrons
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.12" data-path="../Feedback.html">
            
                <a href="../Feedback.html">
            
                    
                    Feedback
            
                </a>
            

            
        </li>
    

    

    <li class="divider"></li>

    <li>
        <a href="https://www.gitbook.com" target="blank" class="gitbook-link">
            Published with GitBook
        </a>
    </li>
</ul>


                </nav>
            
        
    </div>

    <div class="book-body">
        
            <div class="body-inner">
                
                    

<div class="book-header" role="navigation">
    

    <!-- Title -->
    <h1>
        <i class="fa fa-circle-o-notch fa-spin"></i>
        <a href=".." >Example: Reddit API</a>
    </h1>
</div>




                    <div class="page-wrapper" tabindex="-1" role="main">
                        <div class="page-inner">
                            
<div id="book-search-results">
    <div class="search-noresults">
    
                                <section class="normal markdown-section">
                                
                                <h1 id="example-reddit-api">Example: Reddit API</h1>
<p>This is the complete source code of the Reddit headline fetching example we built during the <a href="./">advanced tutorial</a>.</p>
<h2 id="entry-point">Entry Point</h2>
<h4 id="indexjs"><code>index.js</code></h4>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> <span class="hljs-string">&apos;babel-polyfill&apos;</span>

<span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">&apos;react&apos;</span>
<span class="hljs-keyword">import</span> { render } <span class="hljs-keyword">from</span> <span class="hljs-string">&apos;react-dom&apos;</span>
<span class="hljs-keyword">import</span> Root <span class="hljs-keyword">from</span> <span class="hljs-string">&apos;./containers/Root&apos;</span>

render(
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Root</span> /&gt;</span>,
  document.getElementById(&apos;root&apos;)
)
</span></code></pre>
<h2 id="action-creators-and-constants">Action Creators and Constants</h2>
<h4 id="actionsjs"><code>actions.js</code></h4>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> fetch <span class="hljs-keyword">from</span> <span class="hljs-string">&apos;isomorphic-fetch&apos;</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> REQUEST_POSTS = <span class="hljs-string">&apos;REQUEST_POSTS&apos;</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> RECEIVE_POSTS = <span class="hljs-string">&apos;RECEIVE_POSTS&apos;</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> SELECT_SUBREDDIT = <span class="hljs-string">&apos;SELECT_SUBREDDIT&apos;</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> INVALIDATE_SUBREDDIT = <span class="hljs-string">&apos;INVALIDATE_SUBREDDIT&apos;</span>

<span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">selectSubreddit</span>(<span class="hljs-params">subreddit</span>) </span>{
  <span class="hljs-keyword">return</span> {
    type: SELECT_SUBREDDIT,
    subreddit
  }
}

<span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">invalidateSubreddit</span>(<span class="hljs-params">subreddit</span>) </span>{
  <span class="hljs-keyword">return</span> {
    type: INVALIDATE_SUBREDDIT,
    subreddit
  }
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">requestPosts</span>(<span class="hljs-params">subreddit</span>) </span>{
  <span class="hljs-keyword">return</span> {
    type: REQUEST_POSTS,
    subreddit
  }
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">receivePosts</span>(<span class="hljs-params">subreddit, json</span>) </span>{
  <span class="hljs-keyword">return</span> {
    type: RECEIVE_POSTS,
    subreddit,
    posts: json.data.children.map(child =&gt; child.data),
    receivedAt: <span class="hljs-built_in">Date</span>.now()
  }
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchPosts</span>(<span class="hljs-params">subreddit</span>) </span>{
  <span class="hljs-keyword">return</span> dispatch =&gt; {
    dispatch(requestPosts(subreddit))
    <span class="hljs-keyword">return</span> fetch(<span class="hljs-string">`https://www.reddit.com/r/<span class="hljs-subst">${subreddit}</span>.json`</span>)
      .then(response =&gt; response.json())
      .then(json =&gt; dispatch(receivePosts(subreddit, json)))
  }
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">shouldFetchPosts</span>(<span class="hljs-params">state, subreddit</span>) </span>{
  <span class="hljs-keyword">const</span> posts = state.postsBySubreddit[subreddit]
  <span class="hljs-keyword">if</span> (!posts) {
    <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>
  } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (posts.isFetching) {
    <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-keyword">return</span> posts.didInvalidate
  }
}

<span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchPostsIfNeeded</span>(<span class="hljs-params">subreddit</span>) </span>{
  <span class="hljs-keyword">return</span> (dispatch, getState) =&gt; {
    <span class="hljs-keyword">if</span> (shouldFetchPosts(getState(), subreddit)) {
      <span class="hljs-keyword">return</span> dispatch(fetchPosts(subreddit))
    }
  }
}
</code></pre>
<h2 id="reducers">Reducers</h2>
<h4 id="reducersjs"><code>reducers.js</code></h4>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { combineReducers } <span class="hljs-keyword">from</span> <span class="hljs-string">&apos;redux&apos;</span>
<span class="hljs-keyword">import</span> {
  SELECT_SUBREDDIT, INVALIDATE_SUBREDDIT,
  REQUEST_POSTS, RECEIVE_POSTS
} <span class="hljs-keyword">from</span> <span class="hljs-string">&apos;./actions&apos;</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">selectedSubreddit</span>(<span class="hljs-params">state = &apos;reactjs&apos;, action</span>) </span>{
  <span class="hljs-keyword">switch</span> (action.type) {
  <span class="hljs-keyword">case</span> SELECT_SUBREDDIT:
    <span class="hljs-keyword">return</span> action.subreddit
  <span class="hljs-keyword">default</span>:
    <span class="hljs-keyword">return</span> state
  }
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">posts</span>(<span class="hljs-params">state = {
  isFetching: false,
  didInvalidate: false,
  items: []
}, action</span>) </span>{
  <span class="hljs-keyword">switch</span> (action.type) {
    <span class="hljs-keyword">case</span> INVALIDATE_SUBREDDIT:
      <span class="hljs-keyword">return</span> <span class="hljs-built_in">Object</span>.assign({}, state, {
        didInvalidate: <span class="hljs-literal">true</span>
      })
    <span class="hljs-keyword">case</span> REQUEST_POSTS:
      <span class="hljs-keyword">return</span> <span class="hljs-built_in">Object</span>.assign({}, state, {
        isFetching: <span class="hljs-literal">true</span>,
        didInvalidate: <span class="hljs-literal">false</span>
      })
    <span class="hljs-keyword">case</span> RECEIVE_POSTS:
      <span class="hljs-keyword">return</span> <span class="hljs-built_in">Object</span>.assign({}, state, {
        isFetching: <span class="hljs-literal">false</span>,
        didInvalidate: <span class="hljs-literal">false</span>,
        items: action.posts,
        lastUpdated: action.receivedAt
      })
    <span class="hljs-keyword">default</span>:
      <span class="hljs-keyword">return</span> state
  }
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">postsBySubreddit</span>(<span class="hljs-params">state = { }, action</span>) </span>{
  <span class="hljs-keyword">switch</span> (action.type) {
    <span class="hljs-keyword">case</span> INVALIDATE_SUBREDDIT:
    <span class="hljs-keyword">case</span> RECEIVE_POSTS:
    <span class="hljs-keyword">case</span> REQUEST_POSTS:
      <span class="hljs-keyword">return</span> <span class="hljs-built_in">Object</span>.assign({}, state, {
        [action.subreddit]: posts(state[action.subreddit], action)
      })
    <span class="hljs-keyword">default</span>:
      <span class="hljs-keyword">return</span> state
  }
}

<span class="hljs-keyword">const</span> rootReducer = combineReducers({
  postsBySubreddit,
  selectedSubreddit
})

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> rootReducer
</code></pre>
<h2 id="store">Store</h2>
<h4 id="configurestorejs"><code>configureStore.js</code></h4>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { createStore, applyMiddleware } <span class="hljs-keyword">from</span> <span class="hljs-string">&apos;redux&apos;</span>
<span class="hljs-keyword">import</span> thunkMiddleware <span class="hljs-keyword">from</span> <span class="hljs-string">&apos;redux-thunk&apos;</span>
<span class="hljs-keyword">import</span> createLogger <span class="hljs-keyword">from</span> <span class="hljs-string">&apos;redux-logger&apos;</span>
<span class="hljs-keyword">import</span> rootReducer <span class="hljs-keyword">from</span> <span class="hljs-string">&apos;./reducers&apos;</span>

<span class="hljs-keyword">const</span> loggerMiddleware = createLogger()

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">configureStore</span>(<span class="hljs-params">preloadedState</span>) </span>{
  <span class="hljs-keyword">return</span> createStore(
    rootReducer,
    preloadedState,
    applyMiddleware(
      thunkMiddleware,
      loggerMiddleware
    )
  )
}
</code></pre>
<h2 id="container-components">Container Components</h2>
<h4 id="containersrootjs"><code>containers/Root.js</code></h4>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React, { Component } <span class="hljs-keyword">from</span> <span class="hljs-string">&apos;react&apos;</span>
<span class="hljs-keyword">import</span> { Provider } <span class="hljs-keyword">from</span> <span class="hljs-string">&apos;react-redux&apos;</span>
<span class="hljs-keyword">import</span> configureStore <span class="hljs-keyword">from</span> <span class="hljs-string">&apos;../configureStore&apos;</span>
<span class="hljs-keyword">import</span> AsyncApp <span class="hljs-keyword">from</span> <span class="hljs-string">&apos;./AsyncApp&apos;</span>

<span class="hljs-keyword">const</span> store = configureStore()

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Root</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Component</span> </span>{
  render() {
    <span class="hljs-keyword">return</span> (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Provider</span> <span class="hljs-attr">store</span>=<span class="hljs-string">{store}</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">AsyncApp</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">Provider</span>&gt;</span>
    )
  }
}
</span></code></pre>
<h4 id="containersasyncappjs"><code>containers/AsyncApp.js</code></h4>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React, { Component, PropTypes } <span class="hljs-keyword">from</span> <span class="hljs-string">&apos;react&apos;</span>
<span class="hljs-keyword">import</span> { connect } <span class="hljs-keyword">from</span> <span class="hljs-string">&apos;react-redux&apos;</span>
<span class="hljs-keyword">import</span> { selectSubreddit, fetchPostsIfNeeded, invalidateSubreddit } <span class="hljs-keyword">from</span> <span class="hljs-string">&apos;../actions&apos;</span>
<span class="hljs-keyword">import</span> Picker <span class="hljs-keyword">from</span> <span class="hljs-string">&apos;../components/Picker&apos;</span>
<span class="hljs-keyword">import</span> Posts <span class="hljs-keyword">from</span> <span class="hljs-string">&apos;../components/Posts&apos;</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AsyncApp</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Component</span> </span>{
  <span class="hljs-keyword">constructor</span>(props) {
    <span class="hljs-keyword">super</span>(props)
    <span class="hljs-keyword">this</span>.handleChange = <span class="hljs-keyword">this</span>.handleChange.bind(<span class="hljs-keyword">this</span>)
    <span class="hljs-keyword">this</span>.handleRefreshClick = <span class="hljs-keyword">this</span>.handleRefreshClick.bind(<span class="hljs-keyword">this</span>)
  }

  componentDidMount() {
    <span class="hljs-keyword">const</span> { dispatch, selectedSubreddit } = <span class="hljs-keyword">this</span>.props
    dispatch(fetchPostsIfNeeded(selectedSubreddit))
  }

  componentDidUpdate(prevProps) {
    <span class="hljs-keyword">if</span> (<span class="hljs-keyword">this</span>.props.selectedSubreddit !== prevProps.selectedSubreddit) {
      <span class="hljs-keyword">const</span> { dispatch, selectedSubreddit } = <span class="hljs-keyword">this</span>.props
      dispatch(fetchPostsIfNeeded(selectedSubreddit))
    }
  }

  handleChange(nextSubreddit) {
    <span class="hljs-keyword">this</span>.props.dispatch(selectSubreddit(nextSubreddit))
    <span class="hljs-keyword">this</span>.props.dispatch(fetchPostsIfNeeded(nextSubreddit))
  }

  handleRefreshClick(e) {
    e.preventDefault()

    <span class="hljs-keyword">const</span> { dispatch, selectedSubreddit } = <span class="hljs-keyword">this</span>.props
    dispatch(invalidateSubreddit(selectedSubreddit))
    dispatch(fetchPostsIfNeeded(selectedSubreddit))
  }

  render() {
    <span class="hljs-keyword">const</span> { selectedSubreddit, posts, isFetching, lastUpdated } = <span class="hljs-keyword">this</span>.props
    <span class="hljs-keyword">return</span> (
      &lt;div&gt;
        &lt;Picker value={selectedSubreddit}
                onChange={this.handleChange}
                options={[ &apos;reactjs&apos;, &apos;frontend&apos; ]} /&gt;
        &lt;p&gt;
          {lastUpdated &amp;&amp;
            &lt;span&gt;
              Last updated at {new Date(lastUpdated).toLocaleTimeString()}.
              {&apos; &apos;}
            &lt;/span&gt;
          }
          {!isFetching &amp;&amp;
            &lt;a href=&apos;#&apos;
               onClick={this.handleRefreshClick}&gt;
              Refresh
            &lt;/a&gt;
          }
        &lt;/p&gt;
        {isFetching &amp;&amp; posts.length === 0 &amp;&amp;
          &lt;h2&gt;Loading...&lt;/h2&gt;
        }
        {!isFetching &amp;&amp; posts.length === 0 &amp;&amp;
          &lt;h2&gt;Empty.&lt;/h2&gt;
        }
        {posts.length &gt; 0 &amp;&amp;
          &lt;div style={{ opacity: isFetching ? 0.5 : 1 }}&gt;
            &lt;Posts posts={posts} /&gt;
          &lt;/div&gt;
        }
      &lt;/div&gt;
    )
  }
}

AsyncApp.propTypes = {
  selectedSubreddit: PropTypes.string.isRequired,
  posts: PropTypes.array.isRequired,
  isFetching: PropTypes.bool.isRequired,
  lastUpdated: PropTypes.number,
  dispatch: PropTypes.func.isRequired
}

function mapStateToProps(state) {
  const { selectedSubreddit, postsBySubreddit } = state
  const {
    isFetching,
    lastUpdated,
    items: posts
  } = postsBySubreddit[selectedSubreddit] || {
    isFetching: true,
    items: []
  }

  return {
    selectedSubreddit,
    posts,
    isFetching,
    lastUpdated
  }
}

export default connect(mapStateToProps)(AsyncApp)
</code></pre>
<h2 id="presentational-components">Presentational Components</h2>
<h4 id="componentspickerjs"><code>components/Picker.js</code></h4>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React, { Component, PropTypes } <span class="hljs-keyword">from</span> <span class="hljs-string">&apos;react&apos;</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Picker</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Component</span> </span>{
  render() {
    <span class="hljs-keyword">const</span> { value, onChange, options } = <span class="hljs-keyword">this</span>.props

    <span class="hljs-keyword">return</span> (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">span</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>{value}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">select</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{e</span> =&gt;</span> onChange(e.target.value)}
                value={value}&gt;
          {options.map(option =&gt;
            <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{option}</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{option}</span>&gt;</span>
              {option}
            <span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>)
          }
        <span class="hljs-tag">&lt;/<span class="hljs-name">select</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span></span>
    )
  }
}

Picker.propTypes = {
  options: PropTypes.arrayOf(
    PropTypes.string.isRequired
  ).isRequired,
  value: PropTypes.string.isRequired,
  onChange: PropTypes.func.isRequired
}
</code></pre>
<h4 id="componentspostsjs"><code>components/Posts.js</code></h4>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React, { PropTypes, Component } <span class="hljs-keyword">from</span> <span class="hljs-string">&apos;react&apos;</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Posts</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Component</span> </span>{
  render() {
    <span class="hljs-keyword">return</span> (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span>
        {this.props.posts.map((post, i) =&gt;
          <span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{i}</span>&gt;</span>{post.title}<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
        )}
      <span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span></span>
    )
  }
}

Posts.propTypes = {
  posts: PropTypes.array.isRequired
}
</code></pre>

                                
                                </section>
                            
    </div>
    <div class="search-results">
        <div class="has-results">
            
            <h1 class="search-results-title"><span class='search-results-count'></span> results matching "<span class='search-query'></span>"</h1>
            <ul class="search-results-list"></ul>
            
        </div>
        <div class="no-results">
            
            <h1 class="search-results-title">No results matching "<span class='search-query'></span>"</h1>
            
        </div>
    </div>
</div>

                        </div>
                    </div>
                
            </div>

            
                
                <a href="UsageWithReactRouter.html" class="navigation navigation-prev navigation-unique" aria-label="Previous page: Usage with React Router">
                    <i class="fa fa-angle-left"></i>
                </a>
                
                
            
        
    </div>

    <script>
        var gitbook = gitbook || [];
        gitbook.push(function() {
            gitbook.page.hasChanged({"page":{"title":"Example: Reddit API","level":"1.4.5","depth":2,"next":{"title":"Next Steps","level":"1.4.6","depth":2,"ref":"","articles":[]},"previous":{"title":"Usage with React Router","level":"1.4.4","depth":2,"path":"advanced/UsageWithReactRouter.md","ref":"./advanced/UsageWithReactRouter.md","articles":[]},"dir":"ltr"},"config":{"gitbook":"*","theme":"default","variables":{},"plugins":["livereload"],"pluginsConfig":{"livereload":{},"highlight":{},"search":{},"lunr":{"maxIndexSize":1000000,"ignoreSpecialCharacters":false},"sharing":{"facebook":true,"twitter":true,"google":false,"weibo":false,"instapaper":false,"vk":false,"all":["facebook","google","twitter","weibo","instapaper"]},"fontsettings":{"theme":"white","family":"sans","size":2},"theme-default":{"styles":{"website":"styles/website.css","pdf":"styles/pdf.css","epub":"styles/epub.css","mobi":"styles/mobi.css","ebook":"styles/ebook.css","print":"styles/print.css"},"showLevel":false}},"structure":{"langs":"LANGS.md","readme":"README.md","glossary":"GLOSSARY.md","summary":"SUMMARY.md"},"pdf":{"pageNumbers":true,"fontSize":12,"fontFamily":"Arial","paperSize":"a4","chapterMark":"pagebreak","pageBreaksBefore":"/","margin":{"right":62,"left":62,"top":56,"bottom":56}},"styles":{"website":"styles/website.css","pdf":"styles/pdf.css","epub":"styles/epub.css","mobi":"styles/mobi.css","ebook":"styles/ebook.css","print":"styles/print.css"}},"file":{"path":"advanced/ExampleRedditAPI.md","mtime":"2017-03-13T14:28:11.282Z","type":"markdown"},"gitbook":{"version":"3.2.2","time":"2017-03-15T14:47:19.389Z"},"basePath":"..","book":{"language":""}});
        });
    </script>
</div>

        
    <script src="../gitbook/gitbook.js"></script>
    <script src="../gitbook/theme.js"></script>
    
        
        <script src="../gitbook/gitbook-plugin-livereload/plugin.js"></script>
        
    
        
        <script src="../gitbook/gitbook-plugin-search/search-engine.js"></script>
        
    
        
        <script src="../gitbook/gitbook-plugin-search/search.js"></script>
        
    
        
        <script src="../gitbook/gitbook-plugin-lunr/lunr.min.js"></script>
        
    
        
        <script src="../gitbook/gitbook-plugin-lunr/search-lunr.js"></script>
        
    
        
        <script src="../gitbook/gitbook-plugin-sharing/buttons.js"></script>
        
    
        
        <script src="../gitbook/gitbook-plugin-fontsettings/fontsettings.js"></script>
        
    

    </body>
</html>

